package com.nyist.myticket.core.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ClassUtils;

public class UploadUtil {

	public static final String UPLOAD_PATH = "/upload";
	public static final String DATA_PATH = "/data";
	public static final String TEMP_PATH = "/temp";
	public static final String PUBLIC_PATH = "/public";

	public static String getSuffixName(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	public static boolean mkdirs(String path) {
		File file = new File(path);
		if (!file.exists()) {
			return file.mkdirs();
		}
		return true;
	}

	public static String makeFileDir(Date now) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy/MM/dd");
		return dateFormat.format(now);
	}

	public static String makeRandomFileName(Date now, String suffixName) {
		SimpleDateFormat simpleDateFormat;
		simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String nowStr = simpleDateFormat.format(now);
		Random random = new Random();
		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
		return nowStr + rannum + suffixName;
	}

	public static String getBaseDir() {
		String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		if (path.endsWith("/")) {
			path = path.substring(0, path.length() - 1);
		}
		path = path + "/../../..";
		return path + DATA_PATH;
	}

	public static void main(String[] args) {
		System.out.println(UploadUtil.getBaseDir());
	}

	public static void setFileDownloadHeader(HttpServletResponse response, String filename) {
		String headerValue = "attachment;";
		headerValue += " filename=\"" + encodeURIComponent(filename) + "\";";
		headerValue += " filename*=utf-8''" + encodeURIComponent(filename);
		// 设置下载的文件流格式,header 要求就是这样的
		// name = Content-Disposition , value = attachment;filename=URLEncoder.encode(name, "UTF-8")
		response.setHeader("Content-Disposition", headerValue);
		// 设置文件类型为 download 下载类型
		response.setContentType("application/force-download");// 设置强制下载不打开
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
	}

	public static String encodeURIComponent(String value) {
		try {
			return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

}
